<template>
  <div class="common-layout">
    <el-container>
      <el-aside
        :width="isCollapse ? '64px' : '200px'"
        :class="{ collapsed: isCollapse }"
        height="100%"
      >
        <div class="logo-container" @click="router.push('/')">
          <div class="logo">
            <img src="@/assets/pan.png" />
          </div>
          <el-text v-show="!isCollapse" class="mx-1">素材星球</el-text>
        </div>

        <el-menu
          active-text-color="#B1B3B8"
          background-color="#f0f0f0"
          text-color="#000000"
          :collapse="isCollapse"
          collapse-transition
          router
        >
          <!-- <el-menu-item index="0" v-show="!isCollapse">
            <template #title> </template>
          </el-menu-item> -->

          <el-menu-item index="/index" command="/index">
            <el-icon><House /></el-icon>
            <span>首页</span>
          </el-menu-item>

          <el-sub-menu index="0">
            <template #title>
              <el-icon>
                <Avatar />
              </el-icon>
              <span>用户管理</span>
            </template>
            <el-menu-item index="/user" command="/user">
              <el-icon>
                <Avatar />
              </el-icon>
              <span>用户信息</span>
            </el-menu-item>
          </el-sub-menu>
          <el-sub-menu index="1">
            <template #title>
              <el-icon><Memo /></el-icon>
              <span>页面管理</span>
            </template>

            <el-sub-menu index="1-1">
              <template #title>
                <el-icon><Reading /></el-icon>
                <span>主页</span>
              </template>
              <!-- <el-menu-item index="/page/home/total">
                <el-icon><PictureFilled /></el-icon>
                <span>图片数据</span>
              </el-menu-item> -->
              <el-menu-item index="/page/home/banner">
                <el-icon><Picture /></el-icon>
                <span>轮播图</span>
              </el-menu-item>
              <el-menu-item index="/page/home/notice">
                <el-icon><Tickets /></el-icon>
                <span>公告栏</span>
              </el-menu-item>
              <el-menu-item index="/page/home/topic">
                <el-icon><CollectionTag /></el-icon>
                <span>专题精选</span>
              </el-menu-item>
            </el-sub-menu>

            <el-menu-item index="/page/classify">
              <el-icon><Menu /></el-icon>
              <span>分类页</span>
            </el-menu-item>

            <!-- <el-sub-menu index="1-3">
              <template #title>
                <el-icon><VideoCamera /></el-icon>
                <span>素材上传页</span>
              </template>
              <el-menu-item index="/material/upload">
                <el-icon><Upload /></el-icon>
                <span>上传素材记录</span>
              </el-menu-item>
            </el-sub-menu> -->

            <!-- <el-menu-item index="/user/info">
              <el-icon>
                <User />
              </el-icon>
              <span>用户个人页</span>
            </el-menu-item> -->
          </el-sub-menu>

          <el-sub-menu index="2">
            <template #title>
              <el-icon>
                <Tickets />
              </el-icon>
              <span>素材管理</span>
            </template>
            <el-menu-item index="/material/check">
              <el-icon>
                <Tickets />
              </el-icon>
              <span>素材审核</span>
            </el-menu-item>
            <el-menu-item index="/material">
              <el-icon>
                <Tickets />
              </el-icon>
              <span>素材信息</span>
            </el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-aside>
      <!-- 右侧主区域 -->
      <el-container class="right">
        <!-- 头部区域 -->
        <el-header>
          <Navbar
            @dropdown-command="handleDropdownCommand"
            :iconText="false"
            :routeShow="true"
            v-model="isCollapse"
          ></Navbar
        ></el-header>
        <!-- 中间区域 -->
        <el-main>
          <RouterView></RouterView>
        </el-main>
        <!-- 底部区域 -->
        <!-- <el-footer> 右侧footer</el-footer> -->
      </el-container>
    </el-container>
    <updateAvatarDialog
      title="修改头像"
      ref="AvatarDiaglogRef"
      @submitForm="reloadImg"
    >
    </updateAvatarDialog>

    <updatePasswordDialog title="修改密码" ref="updatePasswordDialogRef">
    </updatePasswordDialog>

    <UserInfo ref="ShowUserInfoRef"></UserInfo>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  getCurrentInstance,
  nextTick,
  computed,
  onMounted,
  provide,
  onBeforeUnmount,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute, useRouter } from "vue-router";

import Navbar from "@/components/Navbar.vue";
import updateAvatarDialog from "@/views/user/updateAvatarDialog.vue";
import updatePasswordDialog from "@/components/UpdatePassword/updatePasswordDialog.vue";
import { getAvatar } from "@/api/userinfo";
import { loginOut } from "@/api/login";
// 用户个人资料
import UserInfo from "@/views/user/userinfo.vue";

const { proxy } = getCurrentInstance();
// 路径参数
const route = useRoute();
//  路由
const router = useRouter();
// 左边菜单的隐藏
const isCollapse = ref(false);

const currentPath = ref();

//  获取用户的信息(从cookies中获取)
const userInfo = ref(proxy.VueCookies.get("userInfo"));

const AvatarDiaglogRef = ref();
const updatePasswordDialogRef = ref();
const ShowUserInfoRef = ref();

// 新增：窗口宽度响应式变量
const windowWidth = ref(window.innerWidth);

// 新增：窗口大小变化监听器
const handleResize = () => {
  windowWidth.value = window.innerWidth;
  updateCollapseState();
};

// 新增：根据窗口宽度更新折叠状态
const updateCollapseState = () => {
  isCollapse.value = windowWidth.value < 880;
};

// 获取用户的头像信息
// 调用方法，获取头像数据
const getAvatarImg = async () => {
  // 将头像数据更新至cookies
  // const userInfoData = proxy.VueCookies.get("userInfo");
  // userInfoData.avatarurl =
  // proxy.VueCookies.set("userInfo", userInfo.value.avatarurl);

  await getAvatar(userInfo.value.userId)
    .then((res) => {
      // 判断返回值是否为空
      if (res != null) {
        // 挂载子组件
        userInfo.value.avatarurl = "data:image/png;base64," + res.data;
      }
    })
    .catch((error) => {
      console.log("获取头像失败,使用默认头像！");
      userInfo.value.avatarurl =
        "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png";
    });
};

onMounted(() => {
  getAvatarImg();
  console.log("用户登录信息", userInfo.value);
  // 初始化时设置折叠状态
  updateCollapseState();
  window.addEventListener("resize", handleResize);
});

// 在组件卸载时移除事件监听
onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
});

provide("userInfo", userInfo);

// 下拉菜单
const handleDropdownCommand = (command) => {
  switch (command) {
    case "updateAvatar":
      changeAvatar();
      break;
    case "updatePassword":
      changePassword();
      break;
    case "logOut":
      logout();
      break;
    case "userpage":
      openUserPage();
      break;
    default:
      console.log("未知命令:", command);
  }
};
const changeAvatar = () => {
  AvatarDiaglogRef.value.showUpdateAvatarDialog(userInfo.value);
  // 修改头像的逻辑
  // console.log("修改头像");
};
const reloadImg = () => {
  setTimeout(() => {
    // 重新获取头像
    getAvatarImg();
    // 重新获取个人资料
    ShowUserInfoRef.value.getUserInfoFun();
    console.log("重新获取头像:", userInfo.value);
  }, 300);
};
const changePassword = () => {
  // console.log("修改密码", updatePasswordDialogRef.value);
  // 修改密码的逻辑
  updatePasswordDialogRef.value.showUpdateDialog();
};
const logout = () => {
  // 退出登录的逻辑
  ElMessageBox.confirm("确定要退出吗?", "退出登录", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 清除用户的信息缓存,比如cookies中的
      proxy.VueCookies.set(
        "loginInfo",
        "",
        "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"
      );
      proxy.VueCookies.set(
        "userInfo",
        "",
        "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"
      );

      // 发起请求，请后端发出登出的请求。
      loginOut().then((res) => {
        if (res.code == 200) {
          setTimeout(() => {
            ElMessage.success("成功登出!");
            router.push("/login");
          }, 300);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};

//  打开个人资料页面
const openUserPage = () => {
  // console.log("打开个人资料页面:", ShowUserInfoRef.value);
  ShowUserInfoRef.value.showUserInfo();
};
</script>

<style lang="scss" scoped>
.common-layout {
  // display: flex;
  // height: 100%;
  height: 100vh;
  background: rgb(255, 255, 255);

  .el-aside {
    background: linear-gradient(to right, #dfe9f3 0%, #d5d4d0 100%);
    // min-height: 100%;
    // height: 100%;
    height: 100vh;
    position: relative;
    transition: width 0.3s ease; // 添加平滑过渡效果

    .logo-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 80px;
      .logo {
        display: flex;
        align-items: center;
        justify-content: center;
        // height: 28px;
        width: 100%;
        height: 50%;
        img {
          width: 40px;
        }
      }

      .mx-1 {
        padding-top: 10px;
        color: black;
        font-weight: 500;
        text-align: center; /*设置文字居中*/
        will-change: transform; // 提示浏览器优化动画
        -webkit-animation: swing 2s infinite; /*设置动画*/
        animation: swing 2s infinite;
      }

      @-webkit-keyframes swing {
        /*创建动画*/
        20% {
          -webkit-transform: rotate(15deg);
        }
        40% {
          -webkit-transform: rotate(-15deg);
        }
        60% {
          -webkit-transform: rotate(5deg);
        }
        80% {
          -webkit-transform: rotate(-5deg);
        }
        100% {
          -webkit-transform: rotate(0deg);
        }
      }
      @keyframes swing {
        /*标准动画*/
        20% {
          transform: rotate(15deg);
        }
        40% {
          transform: rotate(-15deg);
        }
        60% {
          transform: rotate(5deg);
        }
        80% {
          transform: rotate(-5deg);
        }
        100% {
          transform: rotate(0deg);
        }
      }
    }

    .el-menu {
      border-right: none;
      background-color: inherit !important;
      :deep(ul) {
        background-color: inherit;
      }
      &-vertical-demo:not(.el-menu--collapse) {
        width: 200px;
        max-height: 100%;
      }

      .el-icon:active {
        color: black;
      }
    }
  }
  .right {
    background: #e9e9e7;
    background-blend-mode: screen;
    display: flex;
    height: 100vh;

    .el-header {
      display: flex;
      align-items: center;
      justify-content: center;
      --el-header-padding: 0 0px;
      padding: var(--el-header-padding);
      box-sizing: border-box;
    }

    .el-footer {
    }
  }
}
</style>
